<template>
	<view class="content">
		<sub-navigationbar url="../getcoupons/getcoupons"></sub-navigationbar>
		<!-- 顶部选项卡 -->
		<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
			<view 
				v-for="(item,index) in tabBars" :key="item.id"
				class="nav-item"
				:class="{current: index === tabCurrentIndex}"
				:id="'tab'+index"
				@click="changeTab(index)"
			>{{item.name}}</view>
		</scroll-view>
		<!-- #ifndef H5 -->
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh
			ref="mixPulldownRefresh" 
			class="panel-content" 
			:top="96" 
			@refresh="onPulldownReresh" 
			@setEnableScroll="setEnableScroll"
		>
		<!-- #endif -->
			<!-- 内容部分 -->
			<swiper 
				id="swiper"
				class="swiper-box" 
				:duration="300" 
				:current="tabCurrentIndex" 
				@change="changeTab"
			>
				<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
					<view class="filter">
						<text class="filter-item" 
							v-for="(i,index) in tabItem.subTabBars"
							:key = "index"
							:class="{'current':tabItem.range==i.id}"
							@click="loadNewsList('refresh',i.id)"
						>{{i.name}}</text>
					</view>
					<scroll-view 
						class="panel-scroll-box" 
						:scroll-y="enableScroll" 
						:scroll-into-view="tabItem.scrollTop"
						@scrolltolower="loadMore"
						@scroll="resetscrollTop"
						>
						<!-- 
							* 新闻列表 
							* 和nvue的区别只是需要把uni标签转为weex标签而已
							* class 和 style的绑定限制了一些语法，其他并没有不同
						-->
						<view 
							v-for="(item, index) in tabItem.newsList" 
							:key="index" 
							class="news-item" 
							:id="'into_'+tabItem.id+index"
						>
							<view class="price">
								<text class="unit" v-if="item.discountType!=='折扣'">¥</text>
								<text class="num">{{item.discountNumber}}</text>
								<text class="discount" v-if="item.discountType=='折扣'">折</text>
							</view>
							<view class="msgs">
								<view class="wrap">
									<text class="name">{{item.couponName | limitFormat}}</text>
									<text class="condition" v-if="item.thresholdMoney">满{{item.thresholdMoney}}减{{item.discountNumber}}</text>
								</view>
								<text class="date-range">{{item.startTime | dateFormat}}至{{item.endTime | dateFormat}}可使用</text>
							</view>
							<view class="category">
								<view class="tag" :class="{'color1':item.couponType=='消费'}">
									<text class="tag-name">{{item.couponType}}券</text>
								</view>
								<view class="detail-btn" @click="navToDetails(item)">查看详情</view>
							</view>
						</view>
						
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		<!-- #ifndef H5 -->
		</mix-pulldown-refresh>
		<!-- #endif -->
		
	</view>
</template>

<script>
	import json from '@/json'
	import subNavigationbar from '@/components/sub-navigationbar.vue';
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	let windowWidth = 0, scrollTimer = false, tabBar;
	const appData = getApp().globalData;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			subNavigationbar
		},
		data() {
			return {
				tabList:[
					{name: '未使用',id: '1'}, 
					{name: '已使用',id: '2'},
					{name: '已过期',id: '3'}
				],
				gIds:null,// 全局id  pid、memberId、openid
				pageIndex:1,
				pageSize:10,
				memberId:1,
				couponType:null,// null 全部 0 充值 1 消费
				
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				subTabBars:[
					{id:0,name:'全部'},
					{id:1,name:'充值'},
					{id:2,name:'消费'}
				]
			}
		},
		filters:{
			dateFormat(v) {
				return v.split('T')[0].replace(/-/g,".");
			},
			limitFormat(v,len) {
				if(!len) len = 10;
				return v.substring(0,len);
			}
		},
		computed:{
			// 0 未使用 1 已使用 3 已过期
			state() {
				let arr = [0,1,3];
				return arr[this.tabCurrentIndex];
			}
		},
		async onLoad(options) {
			let url = window.location.href;
			let params = url.split('?')[1];
			if(params) {
				let arr = params.split('&');
				params = {};
				arr.forEach(val=>{
					let item = val.split('=');
					let value = item[1].split('#')[0]
					params = {...params,[item[0]]:value}
				})
			}
			console.log('options=>',options,'params=>',params)
			this.gIds = params || null;
			uni.setStorageSync('gIds', params)
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.loadNewsList('refresh');
			setTimeout(()=>{
				uni.stopPullDownRefresh()
			},2000)
		},
		methods: {
			resetscrollTop() {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				if(tabItem.scrollTop) tabItem.scrollTop = '';
				console.log(tabItem.scrollTop)
			},
			/**
			 * 数据处理方法在vue和nvue中通用，可以直接用mixin混合
			 * 这里直接写的
			 * mixin使用方法看index.nuve
			 */
			//获取分类
			loadTabbars(){
				// console.log(json.tabList,'json.tabList')
				let tabList = json.tabList;
				tabList.forEach(item=>{
					item.pageIndex = 1;
					item.loaded = false;
					item.newsList = [];
					item.subTabBars = this.subTabBars;
					item.range = 0;
					item.scrollTop = '';
					item.loadMoreStatus = 0;  //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0;
				})
				this.tabBars = tabList;
				this.loadNewsList('add');
			},
			//新闻列表 type 记载状态 range 该状态分类
			loadNewsList(type,range){
				console.log(range)
				let tabItem = this.tabBars[this.tabCurrentIndex];
				//type add 加载更多 refresh下拉刷新
				if(type === 'add'){
					if(tabItem.loadMoreStatus === 2){
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				if(type === 'refresh'){
					tabItem.refreshing = true;
				}
				// #endif
				
				
				// range 0 全部 1 充值 2 消费
				if(range==0 || range) {
					uni.showLoading({
						title:'加载中...',
					})
					tabItem.range = range;
				}
				console.log(tabItem,'=>loadNewsList')
				
				//setTimeout模拟异步请求数据
				setTimeout(()=>{
					let typeArr = [null,0,1];
					let couponType = typeArr[range];
					let datas = `?page.pageIndex=${tabItem.pageIndex}
								&page.pageSize=${this.pageSize}
								&queryValue=
								memberId:${this.gIds.memberId};
								state:${this.state}`;
					if(couponType || couponType==0)datas = datas+`;couponType:${couponType}`;
					uni.request({
						url:appData.baseUrl+appData.api.userCouponList+datas,
						method:"GET",
						success:(res)=>{
							uni.hideLoading();
							let toastIcon = 'none';
							if(res.data.normal==1) {
								// toastIcon = 'success';
								let list = res.data.list;
								if(type === 'refresh'){
									tabItem.newsList = []; //刷新前清空数组
									tabItem.scrollTop = 'into_'+tabItem.id+0;
								}
								list.forEach(item=>{
									tabItem.newsList.push(item);
								})
								//下拉刷新 关闭刷新动画
								if(type === 'refresh'){
									tabItem.pageIndex = 1;
									this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
									// #ifdef APP-PLUS
									tabItem.refreshing = false;
									// #endif
									tabItem.loadMoreStatus = 0;
								}
								if(type=='add') {
									tabItem.pageIndex++;
								}
								//上滑加载 处理状态
								tabItem.loadMoreStatus = list.length <this.pageSize ? 2: 0;
							}else {
								uni.showToast({
									icon:toastIcon,
									title:res.data.msg
								})
							}
						}
					})
					
					// let list = json.newsList;
					// list.sort((a,b)=>{
					// 	return Math.random() > .5 ? -1 : 1; //静态数据打乱顺序
					// })
					// if(type === 'refresh'){
					// 	tabItem.newsList = []; //刷新前清空数组
					// 	tabItem.scrollTop = 'into_'+tabItem.id+0;
					// }
					// list.forEach(item=>{
					// 	item.id = parseInt(Math.random() * 10000);
					// 	tabItem.newsList.push(item);
					// })
					// //下拉刷新 关闭刷新动画
					// if(type === 'refresh'){
					// 	this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
					// 	// #ifdef APP-PLUS
					// 	tabItem.refreshing = false;
					// 	// #endif
					// 	tabItem.loadMoreStatus = 0;
					// }
					// //上滑加载 处理状态
					// if(type === 'add'){
					// 	tabItem.loadMoreStatus = tabItem.newsList.length > 40 ? 2: 0;
					// }
				}, 600)
			},
			//新闻详情
			navToDetails(data){
				data = JSON.stringify(data);
				let url = `/pages/coupon-detail/coupon-detail?data=${data}`; 

				uni.navigateTo({
					url: url
				})
			},
			
			//下拉刷新
			onPulldownReresh(){
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore(){
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable){
				if(this.enableScroll !== enable){
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e){
				
				if(scrollTimer){
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if(typeof e === 'object'){
					index = e.detail.current
				}
				if(typeof tabBar !== 'object'){
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0; 
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if(i === index){
						nowWidth = result.width;
					}
				}
				if(typeof e === 'number'){
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index; 
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(()=>{
					if (width - nowWidth/2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth/2 - windowWidth / 2;
					}else{
						this.scrollLeft = 0;
					}
					if(typeof e === 'object'){
						this.tabCurrentIndex = index; 
					}
					this.tabCurrentIndex = index; 
					
					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					console.log(tabItem,'=>changeTab')
					if(this.tabCurrentIndex !== 0 && tabItem.loaded !== true){
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 300)
				
			},
			//获得元素的size
			getElSize(id) { 
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
		}
	}
</script>

<style lang='scss'>
	page, .content{
		background-color: #f8f8f8;
		height: 100%;
		overflow: hidden;
	}
	
	

	/* 顶部tabbar */
	.nav-bar{
		position: relative;
		z-index: 10;
		height: 96rpx;
		white-space: nowrap;
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,.06);
		background-color: #fff;
		.nav-item{
			display: inline-block;
			width: 150rpx;
			height: 96rpx;
			text-align: center;
			line-height: 100rpx;
			font-size: 32rpx;
			color: #fff;
			position: relative;
			&:after{
				content: '';
				width: 0;
				height: 0;
				border-bottom: 8rpx solid #fff;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}
		.current{
			font-weight: bold;
			font-size: 36rpx;
			&:after{
				width: 35%;
			}
		}
	}

	.swiper-box{
		height: calc(100% - 88rpx);
	}
	.filter {
		height: 124rpx;
		display: flex;
		justify-content: center;
		flex-direction: row;
		padding-top: 34rpx;
		box-sizing: border-box;
		.filter-item{
			width: 128rpx;
			height: 56rpx;
			text-align: center;
			line-height: 56rpx;
			font-size: 28rpx;
			color: $xy-color-default;
			border-radius: 8rpx;
			background-color: $xy-color-default-t30;
			margin: 0 25rpx;
			&.current {
				background-color: $xy-color-default;
				color: #fff;
			}
		}
	}
	.panel-scroll-box{
		height: calc(100% - 124rpx);
		/* #ifdef H5 */
		height: calc(100% - 124rpx - 96rpx);
		/* #endif */
		padding: 0 32rpx;
		box-sizing: border-box;
	}
	
	.news-item{
		position:relative;
		width: 686rpx;
		height: 174rpx;
		background: url(../../static/yhq_bg.png) no-repeat center center /100% 100%;
		display: flex;
		margin:14rpx 0 28rpx;
		.price {
			width: 174rpx;
			min-width: 174rpx;
			background-color: $xy-color-default;
			border-radius:8rpx 0px 0px 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #FFFFFF;
			.unit,.discount{
				font-size: 36rpx;
				transform: translateY(14rpx);
			}
			.num {
				font-size: 72rpx;
				margin: 0 4rpx;
			}
		}
		.msgs {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			padding: 32rpx 0 32rpx 32rpx;
			box-sizing: border-box;
			color: #333333;
			line-height: 1;
			font-size: 32rpx;
			.wrap {
				display: flex;
				flex-direction: column;
				.condition {
					font-size: 24rpx;
					color: #999999;
					margin-top: 10rpx;
				}
			}
			.date-range{
				font-size: 20rpx;
			}
		}
		.category {
			width: 126rpx;
			min-width: 126rpx;
			.tag {
				position: absolute;
				line-height: 4;
				text-align: center;
				right: 22rpx;
				top: -6rpx;
				background-color: #04C083;
				width: 80rpx;
				height: 60rpx;
				font-size: 20rpx;
				color: #FFFFFF;
				&::before {
					position: absolute;
					left: 0;
					top: 60rpx;
					content: '';
					width: 0; 
					height: 0;
					border-width:32rpx 40rpx 40rpx 40rpx;
					border-style: solid;
					border-color:#04C083 transparent transparent transparent;
				}
				&::after {
					position: absolute;
					right: -6rpx;
					top: 0;
					content: '';
					width: 0; 
					height: 0;
					border-width:3rpx;
					border-style: solid;
					border-color:transparent transparent #04C083 #04C083;
				}
				&.color1 {
					background-color: #F8BA01;
					&::before {
						border-color:#F8BA01 transparent transparent transparent;
					}
					&::after {
						border-color:transparent transparent #F8BA01 #F8BA01;
					}
				}
			}
			.detail-btn {
				background-color: $xy-color-default-t30;
				border-radius: 8rpx;
				color: $xy-color-default;
				font-size: 20rpx;
				line-height: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				height: 40rpx;
				width: 104rpx;
				position: absolute;
				right: 14rpx;
				bottom: 24rpx;
			}
		}
	}
</style>
